import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { TreetableComponent, TreeTableNode, lvFlattenTreeData } from '@iux/live';
import { Subject } from 'rxjs';
import { startWith, takeUntil } from 'rxjs/operators';
import { TreetableService } from '../tree-table.service';

@Component({
  selector: 'app-virtual-scroll-subnode',
  templateUrl: './virtual-scroll-subnode.component.html',
  styleUrls: [],
  changeDetection: ChangeDetectionStrategy.OnPush
})

export class VirtualScrollSubnodeComponent implements OnInit {
  data: TreeTableNode[];

  @ViewChild('lvTreeTable', { static: true }) lvTreeTable: TreetableComponent;

  private treeTableDestroy$ = new Subject<void>();

  constructor(private treetableService: TreetableService, private cdr:ChangeDetectorRef) {}

  ngOnInit() {
    this.initAsyncData();
  }

  ngAfterViewInit() {
    this.subscribeRenderChange();
  }

  subscribeRenderChange() {
    this.lvTreeTable.renderDataChange$
      .pipe(
        startWith(this.lvTreeTable.renderData),
        takeUntil(this.treeTableDestroy$)
      )
      .subscribe(() => {
        const flattenData = lvFlattenTreeData(this.lvTreeTable.renderData, null, { getNodeLevel: true }).map(item => item.data);
        this.lvTreeTable.renderData = flattenData;
      });
  }

  initAsyncData() {
    this.treetableService.getUsers().subscribe((res: TreeTableNode[]) => {
      this.data = res;
      this.cdr.markForCheck();
    });
  }

  trackByIndex(index) {
    return index;
  }

  stateChange(e) {
    console.log('条件发生变更', e);
  }

  expandedChange(e) {
    this.data = [...this.data];
  }

  ngOnDestroy(): void {
    this.treeTableDestroy$.next();
    this.treeTableDestroy$.complete();
  }
}
